package com.cyzy.service;

import com.cyzy.entity.Agree;
import com.cyzy.entity.ClassDO;
import com.cyzy.entity.User;
import com.cyzy.mapper.UserMapper;
import com.cyzy.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private JwtUtil jwtUtil;

    public String loginByUsername(String username,String  password){
        User userDO = null;
        
        // 尝试将username转换为数字查询
        try {
            Integer usernameInt = Integer.parseInt(username);
            userDO = userMapper.findByUsername(usernameInt);
        } catch (NumberFormatException e) {
            // 如果不是数字，尝试其他查询方式
        }
        
        // 如果按用户名找不到，尝试按手机号查找
        if (userDO == null){
            userDO = userMapper.findByPhone(username);
        }
        
        // 如果按手机号找不到，尝试按身份证号查找
        if (userDO == null){
            userDO = userMapper.findByIdCard(username);
        }
        
        if (userDO == null){
            throw  new RuntimeException("用户不存在");
        }
        if (!passwordEncoder.matches(password, userDO.getPassword())){
            throw  new RuntimeException("密码错误");
        }
        return jwtUtil.generateToken(String.valueOf(userDO.getId()));
    }

    public String registerUser(User user) {
        // 验证必要字段
        if (user.getPassword() == null || user.getPhone() == null || 
            user.getNickname() == null || user.getRole() == null) {
            throw new IllegalArgumentException("缺少必填字段：密码、手机号、昵称、角色");
        }
        
        // 检查用户名是否已存在
        if (user.getUsername() != null && !user.getUsername().isEmpty()) {
            try {
                Integer usernameInt = Integer.parseInt(user.getUsername());
                User existingUser = userMapper.findByUsername(usernameInt);
                if (existingUser != null) {
                    throw new RuntimeException("用户名已存在");
                }
            } catch (NumberFormatException e) {
                // 如果用户名不是数字，跳过数字用户名检查
            }
        }
        
        // 检查手机号是否已存在
        User existingUserByPhone = userMapper.findByPhone(user.getPhone());
        if (existingUserByPhone != null) {
            throw new RuntimeException("手机号已被注册");
        }
        
        // 检查身份证号是否已存在（如果提供）
        if (user.getIdCard() != null && !user.getIdCard().isEmpty()) {
            User existingUserByIdCard = userMapper.findByIdCard(user.getIdCard());
            if (existingUserByIdCard != null) {
                throw new RuntimeException("身份证号已被使用");
            }
        }
        
        // 不设置username，让数据库触发器自动生成
        user.setUsername(null);

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 执行插入操作
        userMapper.insertUser(user);
        
        // 插入后查询数据库获取实际生成的username
        User insertedUser = userMapper.findById(String.valueOf(user.getId()));
        if (insertedUser != null) {
            return String.valueOf(insertedUser.getUsername());
        }
        
        return null;
    }
    public int updateUser(User user) {
        User userDO = userMapper.findById(user.getId());

        if (userDO == null){
            throw  new RuntimeException("用户不存在");
        }
        //获取当前时间
        Timestamp update = new Timestamp(System.currentTimeMillis());
        user.setUpdateTime(update);
        int i = userMapper.updateUser(user);
        return i;
    }

    public User findById(String id) {
        User userDO = userMapper.findById(id);
        if (userDO == null){
            throw  new RuntimeException("用户不存在");
        }
        return userDO;
    }
    
    /**
     * 根据用户名查找用户
     */
    public User findByUsername(String username) {
        User user = null;
        
        // 尝试将username转换为数字查询
        try {
            Integer usernameInt = Integer.parseInt(username);
            user = userMapper.findByUsername(usernameInt);
        } catch (NumberFormatException e) {
            // 如果不是数字，尝试其他查询方式
        }
        
        if (user == null) {
            user = userMapper.findByPhone(username);
        }
        if (user == null) {
            user = userMapper.findByIdCard(username);
        }
        return user;
    }
    
    /**
     * 更新用户个人信息
     */
    public int updateUserProfile(User user) {
        User existingUser = userMapper.findById(user.getId());
        System.out.println("user"+ user);
        System.out.println("userDO"+existingUser);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 获取当前时间
        Timestamp updateTime = new Timestamp(System.currentTimeMillis());
        user.setUpdateTime(updateTime);
        
        return userMapper.updateUserProfile(user);
    }
    
    /**
     * 修改密码
     */
    public boolean changePassword(String userId, String oldPassword, String newPassword) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }
        
        // 加密新密码
        String encodedNewPassword = passwordEncoder.encode(newPassword);
        
        // 更新密码
        int result = userMapper.updatePassword(userId, encodedNewPassword);
        return result > 0;
    }
    
    /**
     * 实名认证
     */
    public boolean verifyIdentity(String userId, String realName, String idCard) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查身份证号是否已被使用
        User existingUser = userMapper.findByIdCard(idCard);
        if (existingUser != null && !existingUser.getId().equals(userId)) {
            throw new RuntimeException("身份证号已被其他用户使用");
        }
        
        // 更新实名信息
        int result = userMapper.updateIdentityInfo(userId, realName, idCard);
        return result > 0;
    }
    
    /**
     * 更新头像
     */
    public boolean updateAvatar(String userId, String avatarUrl) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        int result = userMapper.updateAvatar(userId, avatarUrl);
        return result > 0;
    }
    
    /**
     * 获取用户统计信息
     */
    public Object getUserStatistics(String userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 构建统计信息
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("userId", user.getId());
        statistics.put("username", user.getUsername());
        statistics.put("nickname", user.getNickname());
        statistics.put("role", user.getRole());
        statistics.put("roleText", user.getRole() == 1 ? "教师" : "学生");
        statistics.put("realNameVerified", user.getRealNameVerified() == 1);
        statistics.put("createTime", user.getCreateTime());
        statistics.put("lastUpdateTime", user.getUpdateTime());
        
        return statistics;
    }

    /**
     * 加入班级
     */
    public int joinClass(String userId, String classCode) {
        Agree result = userMapper.isJoinedClass(userId, classCode);
        if (result != null) {
            return -1;
        }
        return userMapper.joinClass(userId, classCode);
    }


    public ClassDO findClassById(String classId) {
        ClassDO classDO = userMapper.findClassById(classId);
        if (classDO == null) {
            return null;
        }
        classDO.setStudentCount(userMapper.countStudentsInClass(classId));
        classDO.setTeacherName(userMapper.findById(classDO.getTeacherId()).getNickname());
        return classDO;
    }

    //加入班级
    public int joinClassByCode(String userId, String classCode) {
        ClassDO classDO = userMapper.findClassByCode(classCode);
        if (classDO == null) {
            return -1;
        }
        return userMapper.updateUserClass(userId,classDO.getId());
    }
    public String findClassIdByCode(String classCode) {
        ClassDO classDO = userMapper.findClassByCode(classCode);
        if (classDO == null) {
            return null;
        }
        return classDO.getId();
    }
    //查询班级Id
    public int getClassId(String userId) {
        User user = userMapper.findById(userId);
        return user.getClassId();
    }

}
